package com.samoilovich.belarustoday.tools;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.Spannable;
import android.text.TextPaint;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.samoilovich.belarustoday.Constants;
import com.samoilovich.belarustoday.R;

import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Utility {

    // -----------------------------------------------------------------------------------
     public static String convertStreamToString(InputStream is){
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static HttpParams createHttpParams() {
        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Constants.SOCKET_TIMEOUT);

        return params;
    }

    public static void initImageLoader(Context context) {
        ImageLoader imageLoader = ImageLoader.getInstance();

        if (!imageLoader.isInited()) {
            DisplayImageOptions options = new DisplayImageOptions.Builder().resetViewBeforeLoading().cacheInMemory().cacheOnDisc().build();
            ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).discCacheExtraOptions(480, 800, Bitmap.CompressFormat.JPEG, 75)
                    // width, height, compress format, quality
                    .threadPoolSize(2).threadPriority(Thread.MIN_PRIORITY + 2)
                    .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                            // 2 Mb
                            // .memoryCacheSize(2 * 1024 * 1024) // 2 Mb
                    .discCacheFileNameGenerator(new HashCodeFileNameGenerator()).defaultDisplayImageOptions(options).tasksProcessingOrder(QueueProcessingType.LIFO)
                    .enableLogging().build();
            imageLoader.init(config);
        }

    }

    // -----------------------------------------------------------------------------------
    public static View getRatesTabView(Context context, int title, int dividerVisibility) {
        View view = LayoutInflater.from(context).inflate(R.layout.rates_tab_spec_view, null);

        ((TextView) view.findViewById(R.id.textView_tabTitle)).setText(title);
        view.findViewById(R.id.view_divider).setVisibility(dividerVisibility);
        return view;
    }

    public static boolean hasInternetConnection(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info != null && info.isConnectedOrConnecting()) {
            return true;
        }

        return false;
    }

    public static void clearBackStack(FragmentActivity activity) {
        FragmentManager manager = activity.getSupportFragmentManager();

        for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
            manager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    // -----------------------------------------------------------------------------------
    public static void addAppearAnimation(View view) {
        AlphaAnimation animation = new AlphaAnimation(0.0f, 1f);
        animation.setDuration(Constants.ANIMATION_DURATION);
        view.startAnimation(animation);
    }

    public static void addHideAnimation(View view) {
        AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
        animation.setDuration(Constants.ANIMATION_DURATION);
        view.startAnimation(animation);
    }

    // -----------------------------------------------------------------------------------
    // Work with shared preferences
    public static void setPictureLoadingState(Context context, boolean state) {
        SharedPreferences.Editor editor = context.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
        editor.putBoolean(Constants.PICTURE_LOADING_KEY, state);
        editor.commit();
    }

    public static boolean getPictureLoadingState(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
        return preferences.getBoolean(Constants.PICTURE_LOADING_KEY, Constants.PICTURE_LOADING_DEFAULT_STATE);
    }

    // -----------------------------------------------------------------------------------
    public static Spannable getTextWithoutUnderLine(String text) {
        Spannable s = (Spannable) Html.fromHtml(text);
        for (URLSpan u : s.getSpans(0, s.length(), URLSpan.class)) {
            s.setSpan(new UnderlineSpan() {
                public void updateDrawState(TextPaint tp) {
                    tp.setUnderlineText(false);
                }
            }, s.getSpanStart(u), s.getSpanEnd(u), 0);
        }

        return s;
    }

}
